var ws;
$(function(){

    $("ul#chat-list").on("click","li",function(){      //只需要找到你点击的是哪个ul里面的就行
        var _this = $(this);
        _this.removeAttr('style');
        $('.show_talk').hide();
        var fd = _this.attr('data-id');
        var chat_id = _this.attr('data-chat-id');
        $("#show" + fd).show();
        localStorage.setItem('ws_customer_to_id', fd);
        localStorage.setItem('ws_customer_chat_id', chat_id);
        var userInfo = '我在和' + fd + '号聊天';
        $("#userInfo").text(userInfo);
    });
    link();
    // uploadFile();
});

/**
 * 连接服务
 */
function link () {
    ws = new WebSocket("ws://106.12.201.205:9501");//连接服务器
    ws.onopen = function(event){
        alert('连接了');
        sendIdentity();
    };
    ws.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if (data['type'] == 4) {
            show_online_number(data['number']);
            return;
        } else if (data['type'] == 5) {
            show_online_number(data['number']);
            drop_line(data['fd']);
            return;
        }
        localStorage.setItem('ws_customer_id', data['userFd']);
        localStorage.setItem('ws_customer_to_id', data['toUserFd']);
        localStorage.setItem('ws_customer_chat_id', data['chat_id']);
        var myInfo = '我是' + data['userFd'] + '号（客服）';
        if (data['toUserFd']) {
            userInfo = '我在和' + data['toUserFd'] + '号聊天';
        } else {
            userInfo = '';
        }
        $("#myInfo").text(myInfo);
        $("#userInfo").text(userInfo);
        if (data['type'] == 3) {

            return;
        } else if (data['type'] == 6) {
            data['msg'] = "<a href='" + data['url'] + "'>" + data['msg'] + "</a>"
        }
        add_show(data['toUserFd'], replace_em(data['msg']), data['chat_id']);
    };
    ws.onclose = function(event){
        // console.log(event);
         alert("已经与服务器断开连接\r\n当前连接状态："+this.readyState);
        //alert('请登录后重新打开对话框');
    };

    ws.onerror = function(event){
        console.log(event);
        alert("请登录后重新打开对话框！");
    };
}

/**
 * 发送消息
 */
function sendMsg(){
    var msg = $("#text").val();
    if (!msg) {
        alert('消息不能为空');
        return;
    }
    sendJson(msg, 2, '');
}

function sendJson(content, type, url) {
    var ws_customer_to_id = localStorage.getItem('ws_customer_to_id');
    if (!ws_customer_to_id) {
        alert('消息无法发送，对方不在线');
        return;
    }
    if (type == 6) {
        var data = {type:type,userFd:localStorage.getItem('ws_customer_id'),toUserFd:ws_customer_to_id,msg:content, url:url,chat_id:localStorage.getItem('ws_customer_chat_id'),};
    } else {
        var data = {type:type,userFd:localStorage.getItem('ws_customer_id'),toUserFd:ws_customer_to_id,msg:content,chat_id:localStorage.getItem('ws_customer_chat_id'),};
    }

    $("#text").val('');
    var msg = "<div class=\"msg guest\">\n" +
        "                                <div class=\"msg-right\">\n" +
        "                                    <div class=\"msg-host\"><i class=\"ic kh\"></i></div>\n" +
        "                                    <div class=\"msg-ball\">"+ replace_em(content) +"</div>\n" +
        "                                </div>\n" +
        "                            </div>";
    $("#show" + ws_customer_to_id).append(msg);
    ws.send(JSON.stringify(data));
}

function replace_em(str) {
    str = str.replace(/\</g, '&lt;');
    str = str.replace(/\>/g, '&gt;');
    str = str.replace(/\n/g, '<br/>');
    str = str.replace(/\[:([\s\S]+?)\]/g, '<img src="gif/$1.gif" border="0" />');
    str = str.replace(/!\[([\s\S]+?)\]/g, '<img src="$1" border="0" />');
    return str;
}

/**
 * 设置身份
 */
function sendIdentity() {
    var data = {type:3,userFd:localStorage.getItem('ws_customer_id'),identity_type:3,toUserFd:localStorage.getItem('ws_customer_to_id')};
    ws.send(JSON.stringify(data));
}

/**
 * 显示对方发来的消息
 * @param fd
 * @param msg
 */
function add_show(fd, msg, chat_id)
{
    var flag = false;
    $(".chat-obj").each(function(){
        var obj = $(this);
        if (obj.attr('data-id') == fd) {
            obj.attr('style', 'color:#6fbff0');
            flag = true;
        }
    });
    if (!flag) {
        var str = '<li class="rel-item chat-obj" data-id="' + fd + '" data-chat-id="' + chat_id + '" style="color: #6fbff0">' + fd + '号</li>';
        $("#chat-list").append(str);
    }
    var show_id = add_new_dialog(fd);
    var msg = "<div class=\"pnl-list\" id=\"msgs\">\n" +
        "                                <div class=\"msg robot\" id=\"welcome\">\n" +
        "                                    <div class=\"msg-left\" id=\"welcomeLeft\">\n" +
        "                                        <div class=\"msg-host photo\" id=\"welcomeIcon\" style=\"background-image: url(&quot;https://www.v5kf.com/files/icons/201610/14761555537.png&quot;);\"></div>\n" +
        "                                        <div class=\"msg-ball\" id=\"welcomeBall\"><span>" + msg + "</span></div>\n" +
        "                                    </div>\n" +
        "                                </div>";
    $("#" + show_id).append(msg);
}

/**
 * 显示在线人数
 * @param number
 */
function show_online_number(number)
{
    var str = "(在线人数" + number + "人)";
    $("#online_number").html(str)
}

/**
 * todo  处理  后期需优化
 * 用户断开连接后
 * @param fd
 */
function drop_line(fd)
{
    var ws_customer_to_id = localStorage.getItem('ws_customer_to_id');
    if (ws_customer_to_id == fd) {
        var str = "对方已断开连接（" + fd + "号）";
        $("#userInfo").html(str);
        localStorage.setItem('ws_customer_to_id', '');
        localStorage.setItem('ws_customer_chat_id', '');
    }
}

/**
 * 增加一个新的对话框
 * @param fd
 * @returns {string}
 */
function add_new_dialog(fd)
{
    var new_id = 'show' + fd;
    var show_or_hide = '';
    if ($('.show_talk').length != 1) {
        show_or_hide = 'display: none';
    }
    if ($("#" + new_id).length <= 0) {
        var str = '<div class="abs cover pnl-msgs scroll show_talk" style="' + show_or_hide + '" id="show'+fd+'">\n' +
            '                                <div class="msg min time" id="histStart">加载历史消息</div>\n' +
            '                                <div class="pnl-list" id="hists">\n' +
            '                                    <!-- 历史消息 -->\n' +
            '                                </div>\n' +
            '                            </div>';
        $("#all-show").append(str);
    }
    return new_id;
}

/**
 * 转接客服
 */
function transfer() {
    
}

/**
 * 显示 其他在线客服列表
 */
function customer_list() {

}

/**
 * 获取历史记录
 */
function get_history() {

}

/**
 * 撤回消息（3分钟之内可以撤回）
 */
function cancel_msg() {

}

/**
 * 上传文件
 * @param obj
 * @param type
 * @returns {boolean}
 */
function uploadFile() {

    var uploader = WebUploader.create({

        auto: true,
        // swf文件路径
        swf: 'js/Uploader.swf',

        // 文件接收服务端。
        server: 'http://swoole.upload.guardevil.cn/upload.php',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false
    });
    // 当有文件添加进来的时候
    uploader.on( 'fileQueued', function( file ) {
        var $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
            '<img>' +
            '<div class="info">' + file.name + '</div>' +
            '</div>'
            ),
            $img = $li.find('img');


        // $list为容器jQuery实例
        $("#fileList").append( $li );

        // 创建缩略图
        // 如果为非图片文件，可以不用调用此方法。
        // thumbnailWidth x thumbnailHeight 为 100 x 100

    });
    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file, response ) {
        sendJson(response.msg, 6, response.url);
    });
}